package com.zkadmin.controller;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.MouseEvent;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Tree;
import org.zkoss.zul.Treeitem;
import org.zkoss.zul.Window;

import com.zkadmin.entity.SysRole;
import com.zkadmin.renderer.RoleMenuTreeitemRenderer;
import com.zkadmin.renderer.RoleResourceTreeitemRenderer;
import com.zkadmin.service.SysMenuService;
import com.zkadmin.service.SysResourceService;
import com.zkadmin.service.SysRoleService;

@SuppressWarnings("serial")
public class RoleResourceDialogCtrl extends BaseCtrl<Window> {

	@WireVariable
	private SysMenuService sysMenuService;

	@WireVariable
	private SysResourceService sysResourceService;

	@WireVariable
	private SysRoleService sysRoleService;

	private Window win;

	@Wire
	private Tree menuTree;

	@Wire
	private Tree resourceTree;

	private SysRole role;

	@Override
	protected void init(Window win) {
		this.win = win;

		Map<?, ?> args = Executions.getCurrent().getArg();
		if (args != null && !args.isEmpty()) {
			if (args.containsKey("roleId")) {
				long roleId = (Long) args.get("roleId");
				role = sysRoleService.findById(roleId);
			}
		}

		menuTree.setItemRenderer(new RoleMenuTreeitemRenderer(role.getMenus()));
		menuTree.setModel(sysMenuService.getMenuTreeModel(menuTree.isMultiple(), false));

		resourceTree.setItemRenderer(new RoleResourceTreeitemRenderer(role.getResources()));
		resourceTree.setModel(sysResourceService.getResourceTreeModel(true));
	}

	@Listen("onClick=#cancelBtn,#cancelResourceBtn")
	public void closeDialog(MouseEvent e) {
		win.onClose();
	}

	@Listen("onClick=#createRoleMenuBtn")
	public void createRoleMenu(Event e) {
		Set<Treeitem> selectedItems = menuTree.getSelectedItems();
		Set<Long> menuIds = new HashSet<Long>();
		for (Treeitem treeitem : selectedItems) {
			menuIds.add((Long) treeitem.getAttribute("menuId"));
		}
		sysRoleService.correlationMenus(role.getId(), menuIds);
		win.onClose();
	}

	@Listen("onClick=#createRoleResourceBtn")
	public void createRoleResource(Event e) {
		Set<Treeitem> selectedItems = resourceTree.getSelectedItems();
		Set<Long> resourceIds = new HashSet<Long>();
		for (Treeitem treeitem : selectedItems) {
			resourceIds.add((Long) treeitem.getAttribute("resourceId"));
		}
		sysRoleService.correlationResources(role.getId(), resourceIds);
		win.onClose();
	}
}
